package com.mww.chatroom.controller;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class TestWebSocketAPI extends TextWebSocketHandler {
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //这个方法会在webSocket连接建立成功后，被自动调用
        //super.afterConnectionEstablished(session);
        System.out.println("TestAPI连接成功");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //这个方法是在webSocket收到消息后自动被调用
        System.out.println("TextAPI收到消息"+message.toString());
        //session是个会话，里面记录了通信双方是谁，(session中就持有了webSocket的通信连接）
        session.sendMessage(message);

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //这个方法是在连接接受出现异常的时候，自动被调用
        System.out.println("TestAPI连接出现异常");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //这个方法是在连接正常关闭后，自动被调用
        System.out.println("TestAPI连接关闭");
    }
}

